<?php
namespace app\common\lib\model_operate\query;

use app\common\lib\enum\JoinType;
use app\common\lib\model_operate\QueryDevice;
use think\Db;

/**
 * join查询方法
 */
class Join extends QueryDevice
{
    private $joinType = ['INNER', 'RIGHT', 'LEFT', 'FULL'];
    private $config; //所有配置
    private $baseInfo; //主表基础信息
    private $relevance; //关联表信息

    public function __construct($config)
    {
        //dump( $config );exit;
        if (!empty($config)) {
            $this->config    = $config;
            $this->baseInfo  = $config->getBase();
            $this->relevance = $config->getRelevance();
        }
    }

    /**
     * 获取标记信息
     */
    public function getFlags()
    {
        return $this->joinType;
    }

    /**
     * 执行查询
     */
    public function toQuery()
    {
        $fiedsName = array_keys($this->config->getDisplayFields());

        $da = Db::table($this->baseInfo['tableName']);

        $relevanceFields = [];

        if (empty($this->relevance['relevanceTables'])) {
            return $da;
        }

        foreach ($this->relevance['relevanceTables'] as $key => $items) {

            $da = $da->join($items[0], $items[1], $this->joinTypeFormat($items[2]));
            if (!empty($items[3])) {
                $relevanceFields = array_merge($relevanceFields, $items[3]);
            }
        }

        $search = array_keys($relevanceFields);

        foreach ($fiedsName as $key => $value) {
            if (in_array($value, $search)) {
                $value = $relevanceFields[$value];
            } else if (in_array($value, $this->baseInfo['displayFields'])) {
                $value = $this->baseInfo['tableName'] . '.' . $value;
            } else {
                continue;
            }
            $fiedsName[$key] = $value;
        }

        $where = $this->config->getWhere();
        if (!empty($where)) {
            $da = $da->where($where);
        }

        if (!empty($fiedsName)) {
            $da = $da->field($fiedsName);
        }
        return $da;
    }

    private function joinTypeFormat($type)
    {
        $type = strtoupper($type);
        if (!in_array($type, $this->joinType)) {
            return "INNER";
        }
        return $type;
    }

}
